package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //员工登录
    @Override
    public ResultInfo login(String username, String password) {
        //1.根据username查询mapper
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("此用户不存在！");
        }
        //2.密码比较 前端密码 -- md5加密 -- 后端数据库对比
        String md5 = SecureUtil.md5(password);
        if (!md5.equals(employee.getPassword())) {
            return ResultInfo.error("密码错误！");
        }
        //3.判断此账号是否禁用
        if (employee.getStatus() == 0) {
            return ResultInfo.error("此用户已被禁用！");
        }
        //4.登陆成功，返回用户信息
        return ResultInfo.success(employee);
    }

    //员工列表
    @Override
    public List<Employee> findList(String name) {
        return employeeMapper.findList();
    }

    // 新增员工
    @Override
    public void save(Employee employee) {
        //1.补全员工信息
        // 1-1 雪花算法ID生成器
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);
        // 1-2 初始密码
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);
        // 1-3 员工状态
        employee.setStatus(Employee.STATUS_ENABLE);
//        // 1-4 创建、更新时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//        // 1-5 创建、更新人
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);

        //2.调用mapper新增
        employeeMapper.save(employee);
    }

    //回显员工
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }


    //修改员工
    @Override
    public void update(Employee employee) {
        //1.补全信息
//        employee.setUpdateUser(1L);
//        employee.setUpdateTime(new Date());
        //2.调用mapper修改
        employeeMapper.updateById(employee);
    }

}
